#include <iostream>
#include <jsoncpp/json/json.h>
#include <algorithm>
// #include "oj_model.hpp"
#include "oj_model_sql.hpp"

#include "oj_view.hpp"
#include "../com/httplib.h"
namespace lh_control
{
    using namespace lh_model;
    using namespace lh_view;

    // 提供编译服务的主机信息
    class Machine
    {
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}
        std::string ip;  // IP地址
        uint16_t port;   // 端口号
        int load;        // 载荷
        std::mutex *mtx; // 互斥锁
        // 增加载荷
        void IncLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 减少载荷
        void DecLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        int Load()
        {
            int ret_load = 0;
            if (mtx)
                mtx->lock();
            ret_load = load;
            if (mtx)
                mtx->unlock();
            return ret_load;
        }
        void ClearLoad()
        {
            if (mtx)
                mtx->lock();
            load = 0;
            if (mtx)
                mtx->unlock();
        }
    };
    class LoadBalanc
    {
    public:
        LoadBalanc()
        {
            assert(LoadConf(host_conf));
            LOG(INFO) << "加载配置文件成功" << "\n";
        }
        ~LoadBalanc() {}

    public:
        // 读取配置文件
        bool LoadConf(const std::string &conf_path)
        {
            std::ifstream in(conf_path);
            if (!in.is_open())
            {
                LOG(FATAL) << "获取配置文件: " << conf_path << "失败" << "\n";
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                // 解析一行内容
                std::vector<std::string> tokens;
                StringUtil::Split(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "解析 " << line << "失败" << "\n";
                    continue;
                }
                Machine h;
                h.ip = tokens[0];
                h.port = atoi(tokens[1].c_str());
                h.mtx = new std::mutex;
                _online.push_back(_machines.size());
                _machines.push_back(h);
            }
            return true;
        }
        bool Choose(int *id, Machine **pmachine)
        {
            // 选择一个负载最低的主机
            _mtx.lock();
            if (_online.size() == 0)
            {
                // 没有在线主机
                _mtx.unlock();
                LOG(FATAL) << "当前没有在线的编译主机，请及时检查" << "\n";
                return false;
            }
            // 轮询查找最低载荷的主机
            int min_load = _machines[_online[0]].Load();
            *id = _online[0];
            *pmachine = &_machines[_online[0]];
            for (int i = 1; i < _online.size(); i++)
            {
                int tmp_load = _machines[_online[i]].Load();
                if (min_load > tmp_load)
                {
                    *id = _online[i];
                    *pmachine = &_machines[_online[i]];
                }
            }
            _mtx.unlock();
            return true;
        }
        void SetOnline()
        {
            _mtx.lock();
            // 一键在线
            _online.insert(_online.begin(), _offline.begin(), _offline.end());
            _offline.clear();
            _mtx.unlock();
            std::cout << "所有主机上线..." << std::endl;
        }
        void SetOffline(int which)
        {
            for (auto iter = _online.begin(); iter != _online.end(); iter++)
            {
                if (*iter == which)
                {
                    // 将载荷清0
                    _machines[which].ClearLoad();
                    _online.erase(iter);
                    _offline.push_back(which);
                    break;
                }
            }
        }
        void ShowOnAndOff()
        {
            std::cout << "当前在线主机 : ";
            for (auto &e : _online)
                std::cout << _machines[e].ip << ":" << _machines[e].port << ", " << _machines[e].load << std::endl;
            std::cout << "当前离线主机 : ";
            for (auto &e : _offline)
                std::cout << _machines[e].ip << ":" << _machines[e].port << ", " << _machines[e].load << std::endl;
        }

    private:
        std::vector<Machine> _machines; // 所有服务主机信息
        std::vector<int> _online;       // 所有在线主机的下标
        std::vector<int> _offline;      // 所有离线主机的下标
        std::mutex _mtx;                // 互斥锁
    };

    class Control
    {
    public:
        Control() {}
        ~Control() {}
        bool GetQuestionsList(std::string *html)
        {
            // 1. 获取所有题目
            std::vector<Question> question_list;
            if (!_model.GetAllQuestion(&question_list))
            {
                return false;
            }
            // 1.0 对题目列表进行排序
            sort(question_list.begin(), question_list.end(), [](const Question &q1, const Question &q2)
                 { return stoi(q1.number) < stoi(q2.number); });

            // 2. 构建题目列表html
            _view.AllExpandHtml(question_list, html);
            return true;
        }
        bool GetQuestion(const std::string &number, std::string *html)
        {
            Question q;
            if (!_model.GetQuestionByNumber(number, &q))
            {
                return false;
            }
            _view.OneExpandHtml(q, html);
            return true;
        }
        /*
         * in_json :
         *  code  : ""
         *  input : ""
         * */
        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 1. 获取题目信息
            Question q;
            _model.GetQuestionByNumber(number, &q);
            // std::cout<<"q.code : " <<q.tail<<std::endl;
            // std::cout<<"q.climit : " <<q.climit<<std::endl;
            // std::cout<<"q.mlimit : " <<q.mlimit<<std::endl;
            // 2. in_json反序列化，获取用户提交的代码
            Json::Reader reader;
            Json::Value in_value;
            if (!reader.parse(in_json, in_value))
            {
                LOG(ERROR) << "JSON 解析失败: " << reader.getFormattedErrorMessages();
                return;
            }
            std::string code = in_value["code"].asString();
            // 3. 用户代码 + 测试用例, 构建compile_json
            Json::Value compile_value;
            compile_value["code"] = code + q.tail;
            compile_value["input"] = in_value["input"].asString();

            compile_value["cpu_limit"] = q.climit;
            compile_value["mem_limit"] = q.mlimit;
            Json::FastWriter writer;
            std::string compile_json = writer.write(compile_value);
            // LOG(DEBUG) << "compile_json : " << compile_json << "\n";
            // 4. 选择编译运行服务器
            while (true)
            {
                // 选择编译运行服务器
                int id = 0;
                Machine *pmachine = nullptr;
                if (!load_balanc.Choose(&id, &pmachine))
                {
                    LOG(FATAL) << "当前所有主机都已离线，请及时检查" << "\n";
                    break;
                }
                LOG(INFO) << "当前选择主机  " << pmachine->ip << " : " << pmachine->port << "当前主机载荷 : " << pmachine->Load() << "\n";
                pmachine->IncLoad();
                // 5. 发送HTTP请求
                httplib::Client clit(pmachine->ip, pmachine->port);
                if (auto res = clit.Post("/compile_run", compile_json, "application/json;charset=utf-8"))
                {
                    // 请求成功
                    if (res->status == 200)
                    {
                        // 6. 获取结果，构建out_json
                        *out_json = res->body;
                        pmachine->DecLoad();
                        LOG(INFO) << "请求编译运行服务成功..." << "\n";
                        break;
                    }
                    pmachine->DecLoad();
                }
                else
                {
                    // 主机离线
                    LOG(ERROR) << "请求主机id : " << id << "," << pmachine->ip << ":" << pmachine->port << ", 该主机可能离线..." << "\n";
                    load_balanc.SetOffline(id);
                    // load_balanc.ShowOnAndOff();
                }
            }
        }
        void AutoOnline()
        {
            load_balanc.SetOnline();
        }

    private:
        Model _model;
        View _view;
        LoadBalanc load_balanc;
    };
}